<script lang="ts">
    import { ref, defineComponent, computed, onMounted, nextTick, onBeforeUnmount, reactive } from 'vue';
    import { useRoute, useRouter } from 'vue-router';
    import { useShopNav } from '@/store/modules/app';
    import { useUserStore } from '@/store/modules/user';
    import { useI18n } from 'vue-i18n';
    import { showToast, showConfirmDialog } from 'vant';
    import API_HOME from '@/apis/home';
    export default defineComponent({
        name: 'headers',
        props: {
            loading: {
                type: Boolean,
                default: false,
            },
        },
        setup () {
            const { t } = useI18n();
            // 国际化
            const router = useRouter();
            const route = useRoute();
            const appStore = useShopNav();
            const tabBar = computed(() => appStore.getTabBar);
            const badgeNumber = computed(() => appStore.cartList.length);
            let keyWord = ref('')
            let showMenu = ref(false);
            let boxRef = ref(null);

            let isMobile = ref(false);
            let showPop = ref(false);
            let showPopMenu = ref(false);
            let showCartPop = ref(false);
            let userStore = useUserStore();
            let token = ref('');
            let userInfo = computed(() => userStore.userInfo);
            // 跳转页面
            function goPage (data, query) {
                showMenu.value = false;
                if (query) {
                    router.push({
                        path: data,
                        query: query
                    })
                } else {
                    router.push({
                        path: data,
                    })
                }
            }
            onMounted(() => {
                window.addEventListener('resize', checkDevice);
                checkDevice(); // 初始检测
                getCategoryList()
                getTitle()
            });
            onBeforeUnmount(() => {
                window.removeEventListener('resize', checkDevice);
            })
            // 检测设备函数
            const checkDevice = () => {
                isMobile.value = window.innerWidth <= 768;
            };
            // 退出登录
            const logOut = () => {
                showConfirmDialog({
                    title: t('header.SignOut'),
                    message: t('header.confirmSignOut') + '?',
                    confirmButtonText: t('home.confirm'),
                    cancelButtonText: t('home.cancel'),
                }).then(() => {
                    showMenu.value = false;
                    userStore.logout();
                });
            };
            // 打开盒子时添加事件监听
            const openBox = () => {
                nextTick(() => {
                    // 确保在组件挂载后获取 token
                    token.value = userStore.getToken;
                });
                showMenu.value = !showMenu.value;
                // 注意：需要在 nextTick 后添加监听确保 DOM 已渲染
                nextTick(() => {
                    if (showMenu.value) {
                        document.addEventListener('click', handleClickOutside);
                    } else {
                        document.removeEventListener('click', handleClickOutside);
                    }
                });
            };

            // 处理外部点击
            const handleClickOutside = (event) => {
                // 确保引用存在且不是null
                if (!boxRef.value) {
                    // 如果菜单元素不存在，移除监听器
                    document.removeEventListener('click', handleClickOutside);
                    return;
                }
                // 确保点击的不是菜单本身或其子元素
                if (!boxRef.value.contains(event.target)) {
                    showMenu.value = false;
                }
            };
            // PC切换语言
            let showChangelang = () => {
                showPicker.value = !showPicker.value;

            }

            const clearSearch = () => {
                keyWord.value = '';
                showPop.value = false;
            }
            const openSearchPop = () => {

                showPop.value = true;
            }
            let columns = ref([
                { text: 'Apparel', value: '1' },
                { text: 'Accessories', value: '2' },
                { text: 'Digital', value: '3' },

            ]);
            const onConfirm = ({ selectedValues }) => {

                showPopMenu.value = false;
                goPage('/category', { id: selectedValues[0] })

            };

            const onCancel = () => {
                showPopMenu.value = false;
                // showToast('取消')
            };
            let showPicker = ref(false)
            // 关闭弹出
            const closeC = (data) => {
                showPicker.value = false
            }
            // 搜索项
            const onSearch = () => {
                if (keyWord.value.trim() === '') {
                    showToast(t('header.searchKey'));
                    return;
                }
                router.push({
                    path: '/category',
                    query: { keyword: keyWord.value.trim() }
                })
            }
            // 关闭购物车
            const closeCart = () => {
                showCartPop.value = false;
            };
            // 获取分类列表
            const getCategoryList = async () => {
                let res = await API_HOME.goodsCategory()
                if (res.code == 1) {
                    columns.value = res.data.slice(0, 3)
                }
            }
            let shopName = ref('DNS')
            // 获取商品标题
            let getTitle = async () => {
                let res = await API_HOME.indexConfigValue({
                    code: 'name'
                })
                if (res.code == 1) {
                    shopName.value = res.data
                }
            }
            return {
                goPage,
                tabBar,
                keyWord,
                badgeNumber,
                showMenu,
                openBox,
                boxRef,
                isMobile,
                clearSearch,
                showPop,
                openSearchPop,
                columns,
                onCancel,
                onConfirm,
                showPopMenu,
                showCartPop,
                token,
                logOut,
                closeC,
                showPicker,
                onSearch,
                t,
                closeCart,
                userInfo,
                shopName,
                showChangelang
            };
        },
    });
</script>

<template>
    <van-sticky>
        <div class="headers-card">
            <div class="title">
                <div class="left_tit">
                    <h2 @click="goPage('/home')" class="home">{{shopName}}</h2>
                    <div v-if="!isMobile">
                        <span @click="goPage('/category',{id:i.id})" v-for="(i,index) in columns"
                            :key="index">{{i.name}}</span>
                    </div>
                </div>
                <div class="right_tit">
                    <div class="right_box">
                        <div>
                            <van-icon name="search" size="20" v-if="isMobile" style="margin-right: 8px;"
                                @click="openSearchPop" />
                            <van-search v-model="keyWord" :placeholder="t('header.searchKey')" @search="onSearch"
                                :clearable="false" v-else />
                        </div>
                        <!-- 切换语言 -->
                        <div class="language">
                            <img src="@/assets/shop/language.png" style="width: 30px;height: 30px;" id="lang1" alt=""
                                @click="showChangelang">
                            <div class="changelangBox">
                                <!-- 移动端组件 -->
                                <ChangeLang :show="showPicker" @closeLan="closeC"></ChangeLang>
                            </div>

                        </div>
                        <!-- 个人 -->
                        <div class="iconBox" ref="boxRef">
                            <div @click="openBox">
                                <svg t="1753252671544" width="36" height="36" viewBox="0 0 1024 1024" version="1.1"
                                    xmlns="http://www.w3.org/2000/svg" p-id="2268">
                                    <path d="M513 513m-449 0a449 449 0 1 0 898 0 449 449 0 1 0-898 0Z" fill="#e6e6e6"
                                        p-id="2269" data-spm-anchor-id="a313x.search_index.0.i5.17c03a81Y3cVzu"
                                        class="">
                                    </path>
                                    <path d="M519 365m-145 0a145 145 0 1 0 290 0 145 145 0 1 0-290 0Z" fill="#bfbfbf"
                                        p-id="2270" data-spm-anchor-id="a313x.search_index.0.i7.17c03a81Y3cVzu"
                                        class="selected"></path>
                                    <path d="M517 508a255 255 0 0 0-254.672 242h509.344A255 255 0 0 0 517 508z"
                                        fill="#bfbfbf" p-id="2271"
                                        data-spm-anchor-id="a313x.search_index.0.i6.17c03a81Y3cVzu" class="selected">
                                    </path>
                                </svg>
                            </div>
                            <!-- 已登录 -->
                            <div v-if="token">
                                <div class="animate__animated animate__flipInX downMenu" v-show="showMenu">
                                    <div class="account">
                                        <div class="account_log">
                                            <van-image round width="30px" height="30px" :src="userInfo.avatar" />
                                            <div class="account_info">
                                                <div class="name">{{userInfo.username}}</div>
                                                <div>{{userInfo.email}}</div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="account_In" @click="goPage('/user')">
                                        <van-icon name="friends-o" />
                                        <span>{{t('header.Account')}}</span>
                                    </div>
                                    <div class="account_In" @click="logOut">
                                        <van-icon name="revoke" />
                                        <span>{{t('header.SignOut')}}</span>
                                    </div>
                                </div>
                            </div>
                            <!-- 未登录 -->
                            <div v-else>
                                <div class="animate__animated animate__flipInX downMenu" v-show="showMenu">
                                    <div class="account">{{t('header.Account')}}</div>
                                    <div class="account_In" @click="goPage('/login')">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"
                                            viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                                            stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-log-in"
                                            aria-hidden="true">
                                            <path d="m10 17 5-5-5-5"></path>
                                            <path d="M15 12H3"></path>
                                            <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"></path>
                                        </svg>
                                        <span> {{t('header.SignIn')}}</span>
                                    </div>
                                    <div class="account_In" @click="goPage('/register')">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"
                                            viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                                            stroke-linecap="round" stroke-linejoin="round"
                                            class="lucide lucide-user-round-plus" aria-hidden="true">
                                            <path d="M2 21a8 8 0 0 1 13.292-6"></path>
                                            <circle cx="10" cy="8" r="5"></circle>
                                            <path d="M19 16v6"></path>
                                            <path d="M22 19h-6"></path>
                                        </svg>
                                        <span> {{t('header.SignUp')}}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="iconCar" @click="showCartPop=true">
                            <van-badge :content="badgeNumber" position="bottom-right">
                                <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24"
                                    fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                                    stroke-linejoin="round" class="lucide lucide-shopping-bag" aria-hidden="true">
                                    <path d="M16 10a4 4 0 0 1-8 0"></path>
                                    <path d="M3.103 6.034h17.794"></path>
                                    <path
                                        d="M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z">
                                    </path>
                                </svg>
                            </van-badge>
                        </div>
                        <div v-if="isMobile" @click="showPopMenu=true">
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"
                                fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                                stroke-linejoin="round" class="lucide lucide-menu" aria-hidden="true">
                                <path d="M4 12h16"></path>
                                <path d="M4 18h16"></path>
                                <path d="M4 6h16"></path>
                            </svg>
                        </div>

                    </div>
                </div>
            </div>
            <!-- 移动端搜索 -->
            <van-popup v-model:show="showPop" position="top" :style="{ height: '15%' }" @close="clearSearch">
                <div style="margin-top: 10%;">
                    <van-search v-model="keyWord" placeholder="Search Keyword" @search="onSearch" :clearable="false" />
                </div>
            </van-popup>
            <!-- 移动端索引nav -->
            <van-popup v-model:show="showPopMenu" position="bottom">
                <van-picker :title="t('home.Menu')" :columns="columns"
                    :columns-field-names="{ text: 'name', value: 'id'}" @confirm="onConfirm" @cancel="onCancel"
                    :confirm-button-text="t('home.confirm')" :cancel-button-text="t('home.cancel')" />
            </van-popup>
            <!-- 购物车Pop -->
            <van-popup v-model:show="showCartPop" :position="isMobile?'bottom':'right'"
                :style="isMobile ? { height: '70%', width: '100%' } : { width: '30%', height: '100%' } ">
                <div>
                    <Shop_Cart @close-popup="closeCart"></Shop_Cart>
                </div>
            </van-popup>
        </div>
    </van-sticky>
</template>

<style lang="less" scoped>
    @import './index.less';
</style>